<?php

namespace app\api\controller\v48;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\consult\AppConsultGift;
use app\common\cachemodel\consult\AppUserConsultGift;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use think\response\Json;

class ConsultChat extends Auth2
{
    private $appType2 = 2;

    /**
     * 咨询礼包 首页
     * @return Json
     * @throws \Exception
     */
    public function giftIndex()
    {
        $giftPackData = (new AppConsultGift())->getConsultGiftIndexData($this->user['id'] ?? 0);

        if ($this->user['id'])
        {
            $zhunleUserAccountModel = new ZhunleUserAccount();
            $userCoinInfo = $zhunleUserAccountModel->getUserCoinFromCache($this->user['id']);
        } else
        {
            $userCoinInfo =[
                'balance' => 0,
                'password' => 0,
            ];
        }

        $recentPayGiftUserInfo = (new AppUserConsultGift())->getRecentPayGiftUserInfo();

        $resData = [
            'tips' => $recentPayGiftUserInfo,
            'gift_pack_data' => $giftPackData,
            'coin' => (int)($userCoinInfo['balance'] ?? 0),
            'coin_pwd_status' => (isset($userCoinInfo['password']) && $userCoinInfo['password']) ? 1 : 0,
        ];
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取 礼包可用占星师
     * @return Json
     */
    public function getGiftAstr()
    {   // 礼包 商品ID
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $appConsultGiftModel = new AppConsultGift();
        $giftInfo = $appConsultGiftModel->getInfoById($id);
        if (!$giftInfo)
        {
            return show(config('code.error'), '服务异常，礼包不存在');
        }
        // 获取 占星师 热的信息
        $astrHotData = (new ZyhsConsultAstrData())->getRankingList(2);
        //获取当前专区的咨询师列表
        $consultModel = new Zlcr3ConsultAccount();
        $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
        $testUser = $rtcConfig['test_user'] ?? '';
        $testAstrId = $testUser ? explode(',', $testUser) : [];
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {   // 华为 合规情况 只显示 当前占星师数据
            if (Util::IsHuaweiAndOppo())
            {
                $astrIdList = $testAccountConfig['huawei_hg_consult_astr_ids'] ? explode(',', $testAccountConfig['huawei_hg_consult_astr_ids']) : [];
            } else
            {
                $astrIdList = $testAccountConfig['honor_hg_consult_astr_ids'] ? explode(',', $testAccountConfig['honor_hg_consult_astr_ids']) : [];
            }
            $astrIds = [];
            foreach ($astrIdList as $astrIdItem)
            {
                if (!in_array($astrIdItem, $testAstrId) || !in_array($astrIdItem, $giftInfo['exclude_astrs']))
                {
                    $astrIds[] = (int)$astrIdItem;
                }
            }
        } else
        {
            $data = (new ZyhsConsultAstrData())->getRankingList(2);
            foreach ($testAstrId as $value)
            {
                unset($data[$value]);
            }
            foreach ($giftInfo['exclude_astrs'] as $value)
            {
                unset($data[$value]);
            }
            $astrIds = array_keys($data);
        }
        //获取分页后的数据
        $astrConsultInfos = $consultModel->batchGetInfoByIds($astrIds, ['service_duration', 'recommended_nums', 'status', 'tids', 'tags', 'level']);
        $astrInfo = (new ZlcrAstr())->batchGetInfoByIds($astrIds);
        $astrList1 = [];
        $astrList2 = [];
        $workIntro = "";
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {
            $rtcConfig = (new ZyhsConfig())->configInfo('rtc');
            if (Util::IsHuaweiAndOppo())
            {
                if (isset($rtcConfig['huawei_work_intro']) && $rtcConfig['huawei_work_intro'])
                {
                    $workIntro = $rtcConfig['huawei_work_intro'];
                }
            } else
            {
                if (isset($rtcConfig['honor_work_intro']) && $rtcConfig['honor_work_intro'])
                {
                    $workIntro = $rtcConfig['honor_work_intro'];
                }
            }
        }
        // 获取新人福利 免充值 发起连线
        $newUserWelfare = $this->user ? (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']) : null;
        $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
        // 免费 连线 时长
        $freeConsultDuration = $freeRtcDuration > 0 ? 1 : 0;
        if ($freeConsultDuration > 0)
        {
            $consultBtnName = sprintf("免费咨询%d分钟", (int)($freeRtcDuration / 60));
        } else
        {
            $consultBtnName = '连线咨询';
        }
        foreach ($astrHotData as $astrId => $s)
        {   // 热度榜遍历
            if (!isset($astrConsultInfos[$astrId]))
            {
                continue;
            }
            $item = $astrConsultInfos[$astrId];
            $tips = '';
            if ($item['service_duration'])
            {
                $i = ceil($item['service_duration'] / 60);
                $tips .= '服务' . ($i > 2000 ? '2000+' : $i) . '分钟';
            }
            if ($item['recommended_nums'])
            {
                if ($tips)
                {
                    $tips .= '·';
                }
                $tips .= $item['recommended_nums'] . "次被推荐";
            }
            $tags = $consultModel->getTags($item['tags']);
            if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
            {
                $tags = array_values(array_diff($tags, ['星盘']));
            }
            if ($item['status'] == 1)
            {   // 在线
                $astrList1[] = [
                    'name' => $astrInfo[$astrId]['nickname'],
                    'avatar' => $astrInfo[$astrId]['avatar'],
                    'tags_icon' => $consultModel->getTagsIcon($item['tids']),
                    'tags' => $tags,
                    'des' => $workIntro ?: $astrInfo[$astrId]['work_intro'],
                    'status' => 1,
                    'id' => $astrId,
                    'tips' => $tips,
                    'level' => $item['level'],
                    'btn_data' => [['title' => '预沟通', 'type' => 1,], ['title' => $consultBtnName, 'type' => 2,],],
                ];
            } else
            {   // 休息
                $astrList2[] = [
                    'name' => $astrInfo[$astrId]['nickname'],
                    'avatar' => $astrInfo[$astrId]['avatar'],
                    'tags_icon' => $consultModel->getTagsIcon($item['tids']),
                    'tags' => $tags,
                    'des' => $workIntro ?: $astrInfo[$astrId]['work_intro'],
                    'status' => 2,
                    'id' => $astrId,
                    'tips' => $tips,
                    'level' => $item['level'],
                    'btn_data' => [['title' => '预沟通', 'type' => 1,],],
                ];
            }
        }
        $resData = array_merge($astrList1, $astrList2);
        return show(config('code.success'), 'Success.', $resData);
    }
}
